import { createStore, applyMiddleWare } from "./redux"
import { reduxLog } from './redux/redux-log'
import { reduxThunk } from "./redux/redux-thunk"


export type S = {
    name: string,
    age: number
}

type Action = {
    type: 'add'|'minus',
    payload: number
}

const initState: S = {
    name: 'peppa',
    age: 6
}

function reducer(state=initState, action?: Action) {
    if (action?.type === 'add') {
        return {
            ...state,
            age: state.age + action.payload
        }
    }
    if (action?.type === 'minus') {
        return {
            ...state,
            age: state.age - action.payload
        }
    }
    return state
}

export const store = createStore<S, Action>(reducer, applyMiddleWare(reduxThunk, reduxLog))

export const actions = {
    add(n: number) {
        store.dispatch({
            type: 'add',
            payload: n
        })
    },
    minus(n: number) {
        store.dispatch({
            type: 'minus',
            payload: n
        })
    },
    addAsync: (n: number) => {
        let timer = setTimeout(() => {
            store.dispatch({
                type: 'add',
                payload: n
            })
            clearTimeout(timer)
        }, 1000)
    },
    /**
     * redux 只能dispatch(action)
     * reudxThunk可以让redux dispatch一个函数
     * dispatch(dispatch => {})
     */
    minusAsync: (n: number) => {
        const action: Action = {
            type: 'minus',
            payload: n
        }
        const dispatch = store.dispatch as Function
        dispatch((dispatch: Function) => {
            const timer = setTimeout(() => {
                dispatch(action)
                clearTimeout(timer)
            }, 1200)
        })
    }
}

